<template>
  <div>
    <div class="common-layout" style=" margin: 0 30%;">
      <div>
        <el-container>
          <el-aside width="200px">
            角色
            <!-- 使用 el-tree 组件展示树形数据 -->
            <el-tree :data="RoleModel" :highlight-current="true" ref="roleTreeRef" :props="treePropsRole"
              node-key="roleId" @node-click="handleNodeClickRole">
            </el-tree>
            <!-- 显示点击节点的 roleId -->
            <div v-if="AddModel.roleId">你点击的节点的 roleId 是: {{ AddModel.roleId }}</div>
          </el-aside>
          <el-aside width="200px">
            <div>
              <!-- 使用 el-tree 组件 -->
              <el-tree :data="treeData" :default-checked-keys="FanTianMenuId" show-checkbox node-key="menuId"
                :props="defaultPropsMenu" @check-change="handleCheckChange" ref="menuTreeRef" :default-expand-all="true"
                :check-strictly="true"></el-tree>
              <!-- 显示选中的 menuId -->
              <!-- <div>选中的 menuId: {{ AddModel.menuId }}</div>
              {{ "反填菜单id" + FanTianMenuId }} -->
            </div>
          </el-aside>
        </el-container>
      </div>
      <div>
        <el-button type="success" @click="AddRoleMenu">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
//#region import
import { ElMessage, ElMessageBox } from 'element-plus';
import moment from 'moment';
import { compile, computed, nextTick, onMounted, reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router';
import { useCounterStore } from '@/stores/counter';
import DepData from '@/stores/departmentData'
import axios from 'axios';
import { ElTree } from 'element-plus';
import type { AnyColumn } from 'element-plus/es/components/table-v2/src/common.mjs';
//pini保存
const store = useCounterStore();
//跳转
const router = useRouter();

//#endregion


// 获取角色树组件的引用
const roleTreeRef = ref<InstanceType<typeof ElTree>>();
// 获取菜单树组件的引用
const menuTreeRef = ref<InstanceType<typeof ElTree>>();




//#region  获取角色数据(id,名称)

//获取角色的数据
const RoleModel = ref([])
//获取角色数据(id, 名称)
const GetRole = () => {
  axios.get("https://localhost:7174/api/Message/GetRole", {}).then(res => {
    RoleModel.value = res.data.data
    console.log(RoleModel.value, "角色名称")
  })
}
// 定义树的属性配置
const treePropsRole: any = ref({
  label: 'roleName', // 指定节点的标签显示字段为 roleName
  children: [] // 指定子节点字段为 children
});




const AddModel: any = reactive({
  "roleId": "",
  "menuId": []
})

//反填菜单id
const FanTianMenuId = ref([])

// 处理节点点击事件(通过roleId 查询 菜单数据实现反填)
const handleNodeClickRole = (data: any) => {
  //清空节点
  AddModel.menuId = [];
  AddModel.roleId = data.roleId;
  console.log(data.roleId, "搜索角色Id")
  axios.get(`https://localhost:7174/api/RoleMenu/GetMenuNameFanTian?RoleId=${data.roleId}`).then(res => {
    FanTianMenuId.value = res.data.data.map((item: any) => item.menuId)
    console.log(res.data.data, '反填菜单名称res')
    console.log(AddModel.menuId, '反填菜单名称')

    nextTick(() => {
      // 强制更新 el-tree 的选中状态
      if (menuTreeRef.value) {
        menuTreeRef.value.setCheckedKeys(FanTianMenuId.value);
      }
    });
  })
};

//#endregion


//#region  获取菜单数据(id,名称)

//获取菜单的数据
const MenuModel = ref([])
// 存储树形结构的数据
const treeData = ref([]);
//获取菜单数据(id, 名称)
const GetMenu = () => {
  axios.get("https://localhost:7174/api/RoleMenu/GetMenuName").then(res => {
    MenuModel.value = res.data.data
    console.log(MenuModel.value, "赋值MenuModel.value")
    console.log(res.data.data, "获取res.data.data")
    treeData.value = convertToTree(MenuModel.value)
    console.log(treeData.value, "获取树形菜单")
  })
}

// 将普通数组转换为树形结构
const convertToTree = (data: any) => {
  const tree: any = [];
  const map: any = {};

  // 先将每个节点存储到 map 中
  data.forEach((item: any) => {
    map[item.menuId] = { ...item, children: [] };
  });

  // 再根据 parentId 构建树形结构
  data.forEach((item: any) => {
    if (item.parentId === 0) {
      tree.push(map[item.menuId]);
    } else {
      const parent = map[item.parentId];
      if (parent) {
        parent.children.push(map[item.menuId]);
      }
    }
  });
  return tree;
};


// 定义 tree 组件的属性配置
const defaultPropsMenu = {
  children: 'children',
  label: 'menuName'
};



//获取菜单多选值
const handleCheckChanges = () => {
  AddModel.menuId = menuTreeRef.value?.getCheckedKeys() || [];
  console.log(AddModel.menuId, '获取单个选中值')
};

// *** 改动部分开始 ***
// 辅助函数：查找节点
const findNodeById = (data: any[], id: number): any | null => {
  for (const item of data) {
    if (item.menuId === id) {
      return item;
    }
    if (item.children && item.children.length > 0) {
      const found = findNodeById(item.children, id);
      if (found) {
        return found;
      }
    }
  }
  return null;
};

// 获取菜单多选值，修改 handleCheckChange 方法
const handleCheckChange = (node: any, checked: boolean) => {
  AddModel.menuId = menuTreeRef.value?.getCheckedKeys() || [];
  console.log(AddModel.menuId, '获取单个选中值');

  if (checked) {
    let parentId = node.parentId;
    while (parentId) {
      const parentNode = findNodeById(treeData.value, parentId);
      if (parentNode && menuTreeRef.value) {
        // *** 改动部分开始 ***
        // 使用 getCheckedKeys 判断节点是否被选中
        const checkedKeys = menuTreeRef.value.getCheckedKeys();
        if (!checkedKeys.includes(parentNode.menuId)) {
          menuTreeRef.value.setChecked(parentNode, true);
        }
        // *** 改动部分结束 ***
      }
      parentId = parentNode?.parentId || null;
    }
  }
};
// *** 改动部分结束 ***



//#endregion

//#region 添加

const AddRoleMenu = () => {
  if (AddModel.roleId == "") {
    ElMessage.error("请选择角色")
    return;
  }
  console.log(AddModel.menuId)
  console.log(AddModel.roleId)
  axios.post("https://localhost:7272/api/RoleMenu", AddModel).then(res => {
    if (res.data.code == 212) {
      ElMessage.success(res.data.msg)
    }
  })
}

//#endregion



onMounted(() => {
  GetRole()
  GetMenu()
})





</script>

<style scoped></style>